package com.qg.lizhanqi.videosquare.uitlhelp;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.media.ThumbnailUtils;
import android.os.Build;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.ImageView;

import com.qg.lizhanqi.videosquare.R;

import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by zsh2722 on 2016/8/17.
 */
public class ImageLoader {
    private Context mContext;
    private static ImageLoader mImageLoader;
    private ImageCache mImageCache;
    private DiskCache mDiskCache;
    private MediaMetadataRetriever mRetriever;
    private static final String TAG = "李站旗";
    // 线程池,线程数量为CPU的数量
    ExecutorService mExecutorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    private ImageLoader() {
    }

    // 单例模式获取类的对象
    public static ImageLoader getInstance() {
        if (mImageLoader == null) {
            mImageLoader = new ImageLoader();
        }
        return mImageLoader;
    }
    // 初始化imageloader的信息
    public void defaultConfig(Context context) {
        this.mContext = context;
        mImageCache = new ImageCache();
        mDiskCache = new DiskCache(context);
        mRetriever = new MediaMetadataRetriever();
    }
    // 加载图片
    public void displayImage(String url, ImageView imageView) {
        Bitmap bitmap = null;
        // 先从缓存中取图片
        bitmap = mImageCache.get(url);
        Log.i(TAG, "displayImage:标志 "+imageView.getTag());
        Log.i(TAG, "displayImage: 实际传入的"+url);

        Log.i(TAG, "displayImage: 缓存"+bitmap);
        if (bitmap != null) {
            if (imageView.getTag().equals(url)) {
                imageView.setImageBitmap(bitmap);
                Log.i(TAG, "从缓存中设置成功");
            }
            return;
        }
        // 如果在缓存中取不到就在内存中取
        bitmap = mDiskCache.get(url);
        Log.i(TAG, "displayImage: 卡"+bitmap);
        if (bitmap != null) {
            Log.i(TAG, "displayImage: 是否一致？"+imageView.getTag().equals(url));
            if (imageView.getTag().equals(url)) {
                imageView.setImageBitmap(bitmap);
                Log.i(TAG, "从内存设置成功");
            }
            return;
        }
        // 如果在内存中取不到,就进行网络请求图片
        imageView.setImageResource(R.drawable.ic_launcher);//暂时没有
        submitLoadRequest(url,imageView);
    }
    //子线程更新UI这里应该有错误
    private void submitLoadRequest(final String imageUrl, final ImageView imageView) {
        imageView.setTag(imageUrl);
        mExecutorService.submit(new Runnable() {
            @Override
            public void run() {
                Log.d("ImageLoader", "从网络中获取"+imageUrl);
                //Bitmap bitmap=downLoadImage(imageUrl);
                Bitmap bitmap=createVideoThumbnail(imageUrl,300,200);
                if (bitmap==null) {
                    return;
                }
                Log.i(TAG, "run: 是否一致："+imageView.getTag().equals(imageUrl)+"请求后bitmap"+bitmap);
                Log.i(TAG, "displayImage: 网络请求标志"+imageView.getTag());
                Log.i(TAG, "displayImage: 网络请求地址："+imageUrl);
                if (imageView.getTag().equals(imageUrl)) {
                    Log.i(TAG, "run: 设置网络请求后的图片");
                    imageView.setImageBitmap(bitmap);
                    Log.i(TAG, "run: 网络请求图片已经设置完成");
                    imageView.invalidate();
                }
                mImageCache.put(imageUrl,bitmap);
                mDiskCache.put(imageUrl,bitmap);
                Log.i(TAG, "run: 网络请求数据已经缓存");
            }
        });
    }
    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    private Bitmap createVideoThumbnail(String url, int width, int height) {
        Log.i("李站旗", "createVideoThumbnail: ");
        Bitmap bitmap = null;
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        int kind = MediaStore.Video.Thumbnails.MINI_KIND;
        try {
            if (Build.VERSION.SDK_INT >= 14) {
                retriever.setDataSource(url, new HashMap<String, String>());
            } else {
                retriever.setDataSource(url);
            }
            bitmap = retriever.getFrameAtTime();
        } catch (IllegalArgumentException ex) {
            // Assume this is a corrupt video file
        } catch (RuntimeException ex) {
            // Assume this is a corrupt video file.
        } finally {
            try {
                retriever.release();
            } catch (RuntimeException ex) {
                // Ignore failures while cleaning up.
            }
        }
        if (kind == MediaStore.Images.Thumbnails.MICRO_KIND && bitmap != null) {
            bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
                    ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
        }
        return bitmap;
    }
    private Bitmap downLoadImage(String imageUrl) {
        Bitmap bitmap = null;
		//获取第一帧
        mRetriever.setDataSource(imageUrl, new HashMap<String, String>());
        bitmap = mRetriever.getFrameAtTime(1);
        return bitmap;
    }
}
